package com.base.common.utils;

import com.base.common.ConfigConstants;
import com.base.common.enums.SmsReportStatus;
import com.base.common.persistent.dao.SmsMapper;
import com.base.common.persistent.dao.SmsReportMapper;
import com.base.common.persistent.model.Sms;
import com.base.common.persistent.model.SmsReport;
import com.cjy.common.bean.ParseMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpStatus;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * easy ui 工具封装类
 * 2013-12-6 上午9:53:49
 * 
 * @author jay.zhoujingjie
 */
@Service("easyUtil")
public class EasyUtil {
	
	public static void main(String[] args) {
		System.out.println(rc4("Hello", "cjy"));
	}
	
	/**
	 * RC4算法加密
	 * 
	 * @param aInput
	 * @param aKey
	 * @return
	 * @author kat.luhongkai
	 */
	public static String rc4(String aInput, String aKey) {
        int[] iS = new int[256];
        byte[] iK = new byte[256];
 
        for (int i = 0; i < 256; i++)
            iS[i] = i;
 
        int j = 1;
 
        for (short i = 0; i < 256; i++) {
            iK[i] = (byte) aKey.charAt((i % aKey.length()));
        }
 
        j = 0;
 
        for (int i = 0; i < 255; i++) {
            j = (j + iS[i] + iK[i]) % 256;
            int temp = iS[i];
            iS[i] = iS[j];
            iS[j] = temp;
        }
 
        int i = 0;
        j = 0;
        char[] iInputChar = aInput.toCharArray();
        char[] iOutputChar = new char[iInputChar.length];
        for (short x = 0; x < iInputChar.length; x++) {
            i = (i + 1) % 256;
            j = (j + iS[i]) % 256;
            int temp = iS[i];
            iS[i] = iS[j];
            iS[j] = temp;
            int t = (iS[i] + (iS[j] % 256)) % 256;
            int iY = iS[t];
            char iCY = (char) iY;
            iOutputChar[x] = (char) (iInputChar[x] ^ iCY);
        }
 
        return new String(iOutputChar);
    }
	
	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 * @throws IOException
	 */
	private static String sendPost() throws IOException, HttpException {
		HttpClient httpClient = new HttpClient();
		httpClient.getParams().setBooleanParameter(
				"http.protocol.expect-continue", false);
		PostMethod getMethod = new PostMethod(ConfigConstants.MESSAGE_URL);
		String content = java.net.URLEncoder.encode(
				ConfigConstants.MESSAGE_MSG, "UTF-8");
		NameValuePair[] data = {
				new NameValuePair("UserID", ConfigConstants.MESSAGE_USER_ID),
				new NameValuePair("Account", ConfigConstants.MESSAGE_NAME),
				new NameValuePair("Password", ConfigConstants.MESSAGE_PWD),
				new NameValuePair("Phones", ConfigConstants.MESSAGE_DST),
				new NameValuePair("SendType", "1"),
				new NameValuePair("SendTime", ""),
				new NameValuePair("PostFixNumber", "1"),
				new NameValuePair("Content", content) };
		getMethod.setRequestBody(data);
		getMethod.addRequestHeader("Connection", "close");
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			byte[] responseBody = getMethod.getResponseBody();
			String str = new String(responseBody, "GBK");
			if (str.contains("GBK")) {
				str = str.replaceAll("GBK", "utf-8");
			}
			System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return getMethod.getResponseBodyAsString();
	}
	
	/**
	 * 返回树形list
	 * 
	 * @param list
	 * @param parse
	 * @return List<Map<String,Object>>
	 * @author jay.zhoujingjie
	 */
	public static <T> List<Map<String, Object>> toTreeList(List<T> list,ParseMap<T> parse)
	{
		List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
		/*for(Iterator<T> iterator = list.iterator();iterator.hasNext();)
		{
			results.add(parse.parse(iterator.next()));
		}*/
		results.add(parse.parse(list));
		return results;
	}
	
	@Resource
	private SmsMapper smsMapper;
	
	@Resource
	private SmsReportMapper smsReportMapper;
	
	/**
	 * 添加短消息
	 * 
	 * @param categories
	 * @param title
	 * @param context
	 * @param receivePhone
	 * @param type
	 * @param smsId
	 * @param reveiveTerminalId
	 * @param senderTerminalId
	 * @return
	 */
	@Transactional
	public Sms addSms(int categories, String title, String context, String receivePhone, int type, int smsId, int reveiveTerminalId, int senderTerminalId) {
		Sms sms = new Sms();
		sms.setCategories(categories);
		sms.setType(type);
		sms.setTitle(title);
		sms.setCreateTime(new Date());
		String uuid = IDGenerator.getUUID().replace("-", "");
		sms.setUuid(uuid.trim());
		sms.setContext(context);
		smsMapper.addSms(sms);
		
		SmsReport smsReport = new SmsReport();
		smsReport.setSendTime(new Date());
		smsReport.setStatus(SmsReportStatus.NOTREAD.getValue());
		smsReport.setSms(smsMapper.querySmsByFuzzyCondition(uuid.trim(), 0, 0, 0, 0, 0, -2).get(0));
		smsReport.setReceivePhone(receivePhone);
		smsReport.setReceiveVisibleness(0);
		smsReport.setSenderVisibleness(0);
		smsReport.setReceiveTerminalId(reveiveTerminalId);
		smsReportMapper.addSmsReport(smsReport);
		return sms;
	}
	
	/**
	 * 
	 * 
	 * @param fileUrl url
	 * @param path 文件保存路径
	 * @throws IOException 
	 */
	public String downloadFile(String fileUrl, String basePath,
			String sysImagesFile, String picUrls) throws IOException {
		String[] fileUrls = fileUrl.split(";");
		String realPath = ServletActionContext.getServletContext().getRealPath(
				sysImagesFile);
		File f = new File(realPath);
		if(!f.exists()){
			f.mkdir();
		}
		for(int i = 0; i < fileUrls.length; i++){
			String[] fileNames = fileUrls[i].split("/"); // 获取文件名
			
			URL url = new URL(fileUrls[i]);	// 构造url
			URLConnection urlConnection = url.openConnection();	// 打开连接
			String saveUrl = realPath + "\\" + fileNames[fileNames.length - 1];
			saveUrl = saveUrl.replaceAll("\\\\", "/");
			if("".equals(picUrls.trim())) {
				picUrls += basePath + sysImagesFile + "/" + fileNames[fileNames.length - 1];
			} else {
				picUrls += ";" + basePath + sysImagesFile + "/" + fileNames[fileNames.length - 1];
			}
			
			DataInputStream dataInputStream = null;
			DataOutputStream dataOutputStream = null;
			dataInputStream = new DataInputStream(urlConnection.getInputStream());
			dataOutputStream = new DataOutputStream(new FileOutputStream(
					new File(saveUrl)));
			IOUtils.copy(dataInputStream, dataOutputStream);
			dataOutputStream.flush();
			if (dataInputStream != null) {
				dataInputStream.close();
			}
			if (dataOutputStream != null) {
				dataOutputStream.close();
			}
		}
		return picUrls;
	}
	
	/**
	 * 按照yyyy-MM-dd HH:mm:ss格式化日期，返回日期字符串
	 * 
	 * @param date
	 * @return
	 */
	public String getDateStrByGeneral(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}
	
	/**
	 * 创建工单保存图片
	 * @param files	文件流数组
	 * @param basePath	项目根路径
	 * @param sysImagesFile	文件存放文件夹路径
	 * @param fileNames	文件名数组
	 * @param picUrls	文件保存后的url
	 * @return
	 * @throws IOException 
	 */
	public String savePictures(File[] file, String basePath,
			String sysImagesFile, String[] fileNames, String picUrls) throws IOException {
		String realPath = ServletActionContext.getServletContext().getRealPath(
				sysImagesFile);
		System.out.println(realPath);
		System.out.println(basePath);
		System.out.println(sysImagesFile);
		File f = new File(realPath);
		if(!f.exists()){
			f.mkdir();
		}
		
		for(int i = 0; i < fileNames.length; i++){
			String url = realPath + "\\" + fileNames[i];
			url = url.replaceAll("\\\\", "/");
			if("".equals(picUrls.trim())) {
				picUrls += basePath + sysImagesFile + "/" + fileNames[i];
			} else {
				picUrls += ";" + basePath + sysImagesFile + "/" + fileNames[i];
			}
			
			DataInputStream dataInputStream = null;
			DataOutputStream dataOutputStream = null;
			dataInputStream = new DataInputStream(new FileInputStream(
					file[i]));
			dataOutputStream = new DataOutputStream(new FileOutputStream(
					new File(url)));
			IOUtils.copy(dataInputStream, dataOutputStream);
			dataOutputStream.flush();
			if (dataInputStream != null) {
				dataInputStream.close();
			}
			if (dataOutputStream != null) {
				dataOutputStream.close();
			}
		}
		return picUrls;
	}
	
	/**
	 * 发送短信
	 * 
	 * @param message	消息内容
	 * @param phoneNo	手机号
	 * @return
	 */
	public boolean sendSms(String message, String phoneNo) {
		/*
		 * TsmsSendCache tsmsSendCache = new TsmsSendCache();
		 * tsmsSendCache.setdBeginTime(new Date());
		 * tsmsSendCache.setnContentType(70);
		 * tsmsSendCache.setsSendNo(phoneNo.trim());
		 * tsmsSendCache.setsSmsMessage(message); int counts =
		 * tsmsSendCacheMapper.addTsms(tsmsSendCache); if(counts != 1) { return
		 * false; }
		 */
		ConfigConstants.MESSAGE_DST = phoneNo;
		ConfigConstants.MESSAGE_MSG = message + "【城际云】";
		try {
			sendPost();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (HttpException e) {
			e.printStackTrace();
		}
		return true;
	}
}
